import sys
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options


if __name__ == '__main__':
    keyword = 'iphone'
    if len(sys.argv) > 1:
        keyword = sys.argv[1]

    op = Options()
    op.add_argument('--headless')

    # driver = webdriver.Chrome(chrome_options=op)
    driver = webdriver.Chrome()
    driver.get('https://www.jd.com')

    # 获取输入框
    kw = driver.find_element_by_id('key')
    # 将keyword信息输入
    kw.send_keys(keyword)
    # 回车
    kw.send_keys(Keys.RETURN)

    # 等页面加载
    time.sleep(3)

    # 点击按销量排序
    sort = driver.find_element_by_xpath('.//div[@class="f-sort"]/a[2]')
    sort.click()
    # 等待页面加载
    time.sleep(3)

    # 向下滚动页面
    driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
    # 等页面加载1秒
    time.sleep(1)
    # 获取所有的商品节点
    products = driver.find_elements_by_class_name('gl-item')
    print(len(products))
    for p in products:
        sku = p.get_attribute('data-sku')
        print(sku)
        # 获取图片标签
        img = p.find_element_by_xpath('.//img')
        # 获取图片标签的src属性
        print(img.get_attribute('src'))

    # 获取完当前页跳转下一页
    # 当最后一页时关闭浏览器
    while True:
        # 每次获取点击下一页等页面加载
        time.sleep(2)
        next_but = driver.find_element_by_css_selector('.pn-next')
        while 'disabled' in next_but.get_attribute('class'):
            driver.quit()
        next_but.click()
